package interpreter.bytecodes;

import interpreter.VirtualMachine;
import java.util.NoSuchElementException;
import java.util.Vector;

/**
 *
 * @author Kristofer Selbekk
 */
public class StoreByteCode extends ByteCode {
    private int offset;
    private String id; // For comment only
    private int topOfStack;
    
    /**
     * Initializes the byte code with two arguments
     */
    public void init( Vector<String> args ) {
        try {
            offset = Integer.parseInt(args.get(0));
            id = args.get(1);
        } catch( NumberFormatException nfe ) {
            // If bad format
            System.out.println("Bad format!");
            System.exit(-1);
        } catch( NoSuchElementException nse ) {
            // If empty argument
            System.out.println("Empty vector!");
            System.exit(-1);
        } catch( NullPointerException npe ) {
            // If argument missing
            System.out.println("Argument given = null.");
            System.exit(-1);
        }
    }

    /**
     * Action: Store top of stack to given offset
     *
     * @param rt the Virtual Machine reference
     */
    public void exec( VirtualMachine rt ) {

        topOfStack = rt.getTopOfStack();
        // Tells the virtual machine to do the down and dirty
        rt.store( offset );
    }

    public Object getArgs() {
        return offset + " " + id;
    }

    public String toString() {

        return super.toString() + "\t"+id+" = "+ topOfStack;
    }
}
